package cc.xpcas.raft.component;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;

/**
 * @author xp
 */
public class SimpleThreadFactory implements ThreadFactory {

    private final String namePrefix;

    private final AtomicInteger count = new AtomicInteger(0);

    private final Consumer<Thread> threadInitializer;

    public SimpleThreadFactory(String namePrefix, Consumer<Thread> threadInitializer) {
        this.namePrefix = namePrefix;
        this.threadInitializer = threadInitializer;
    }

    public SimpleThreadFactory(String namePrefix) {
        this(namePrefix, null);
    }

    private String nextThreadName() {
        return namePrefix + "-" + count.incrementAndGet();
    }

    @Override
    public Thread newThread(Runnable runnable) {
        ThreadGroup group = Optional.ofNullable(System.getSecurityManager())
                .map(SecurityManager::getThreadGroup).orElse(Thread.currentThread().getThreadGroup());
        Thread thread = new Thread(group, runnable, nextThreadName(), 0);
        if (thread.isDaemon()) thread.setDaemon(false);
        if (thread.getPriority() != Thread.NORM_PRIORITY) thread.setPriority(Thread.NORM_PRIORITY);
        if (threadInitializer != null) threadInitializer.accept(thread);
        return thread;
    }
}
